/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.dao.impl.oracle;

import cn.easyplatform.entities.beans.table.TableField;
import cn.easyplatform.studio.dao.Dialect;
import cn.easyplatform.studio.dao.Page;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
class OracleDialect extends Dialect {

    @Override
    protected String getPageBefore(Page page) {
        return "SELECT * FROM (SELECT T.*, ROWNUM RN FROM (";
    }

    @Override
    protected String getPageAfter(Page page) {
        int start = (page.getPageNo() - 1) * page.getPageSize() + 1;
        StringBuilder after = new StringBuilder();
        after.append(") T WHERE ROWNUM <");
        after.append(start + page.getPageSize());
        after.append(") WHERE RN >=");
        after.append(start);
        return after.toString();
    }

    @Override
    public String evalFieldType(TableField mf) {
        switch (mf.getType()) {
            case BOOLEAN:
                return "NUMBER(1)";
            case CLOB:
                return "CLOB";
            case VARCHAR:
                return "VARCHAR2(" + mf.getLength() + ")";
            case LONG:
                return "INTEGER";
            case INT:
                // 用户自定义了宽度
                if (mf.getLength() > 0)
                    return "NUMBER(" + mf.getLength() + ")";
                return "NUMBER(8)";
            case NUMERIC:
                // 用户自定义了精度
                if (mf.getLength() > 0 && mf.getDecimal() > 0) {
                    return "NUMBER(" + mf.getLength() + "," + mf.getDecimal() + ")";
                } else
                    // 用默认精度
                    return "NUMBER(15,2)";
            case TIME:
            case DATETIME:
            case DATE:
                return "DATE";
            default:
                return super.evalFieldType(mf);
        }
    }

    @Override
    public String evalField(String field) {
        return field;
    }
}
